<template>
  <div>
    <el-dialog
      v-model="props.isShow"
      :title="props.isAdd ? '添加' : '编辑'"
      center
      :before-close="cancel"
    >
      <el-form ref="roleRef" :model="roleForm" :rules="rules">
        <el-form-item label="角色名称" :label-width="formLabelWidth" prop="rolename">
          <el-input autocomplete="off" v-model="roleForm.rolename" />
        </el-form-item>
        <el-form-item label="角色权限" :label-width="formLabelWidth">
          <el-tree
            ref="tree"
            :data="store.getters['menu/getMenu']"
            show-checkbox
            node-key="id"
            default-expand-all
            check-strictly
            :props="defaultProps"
          />
        </el-form-item>
        <el-form-item label="状态" :label-width="formLabelWidth">
          <el-tooltip :content="'Switch value: ' + value" placement="top">
            <el-switch
              v-model="roleForm.status"
              style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ccc"
              :active-value="1"
              :inactive-value="2"
            />
          </el-tooltip>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="cancel(roleRef)">取消</el-button>
          <el-button type="primary" @click="confirm(roleRef)"> 确定 </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { defineProps, defineEmits } from "vue";
import { reactive, ref } from "vue";
import type { FormInstance, FormRules } from "element-plus";
import { useStore } from "vuex";
import { roleadd, roleedit, roleinfo } from "../../request/api";
import { ElMessage } from "element-plus";
import role from "../../store/modules/role";

const dialogTableVisible = ref(false);
const dialogFormVisible = ref(false);
const formLabelWidth = "140px";
const value = ref("1");
const store = useStore();
const tree = ref<any>(null);

const rules = {
    rolename: [
        {
            required: true,
            message: "请输入角色名称",
            trigger: "blur",
        },
        {
            min: 2,
            max: 6,
            message: "长度在 2 到 6 个字符",
            trigger: "blur",
        },
    ],
}

let roleForm = ref({
  rolename: "", // 角色名称 string
  menus: "", // 角色权限 id数组 '2,3,4' 字符串
  status: 1, // 状态1正常2禁用 number
});

let props = defineProps({
  isShow: Boolean,
  isAdd: Boolean,
});
let emit = defineEmits(["cancel"]);
let roleRef = ref<FormInstance>();
// 封装取消事件
let cancel = (formEl?: FormInstance | undefined) => {
  emit("cancel");
  roleForm.value = {
    rolename: "", // 角色名称 string
    menus: "", // 角色权限 id数组 '2,3,4' 字符串
    status: 1, // 状态1正常2禁用 number
  };
  if (!formEl) return;
  // 重置权限 通过keys设置目前勾选的节点，使用此方法设置node-key属性
  tree.value.setCheckedKeys([]);
};
const defaultProps = {
  children: "children",
  label: "title",
};
// 防止了必须得点一下菜单列表才可以触发的 单独点角色列表就可以了
store.dispatch("menu/getMenuActions");
// 数据回显
let lookup = async (id: number) => {
  let result: any = await roleinfo({ id });
  // console.log(result);
  if (result.code == 200) {
    roleForm.value = result.list;
    tree.value.setCheckedKeys(roleForm.value.menus.split(","));
    // 修改的时候 需要id
    roleForm.value.id = id;
  }
};
const confirm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate((val) => {
    if (val) {
      roleForm.value.menus = tree.value.getCheckedKeys().join(",");
      if (!roleForm.value.menus) {
        ElMessage({
          message: "该角色没有权限吗？啊！",
          type: "error",
        });
        return;
      }
      if (props.isAdd) {
        // 添加
        // console.log(roleForm.value);
        roleadd(roleForm.value).then((res) => {
          if (res.code == 200) {
            // 成功 提示
            ElMessage.success(res.msg);
            // 成功-关闭弹窗
            cancel();
            store.dispatch("role/getRoleActions");
          } else {
            ElMessage.error(res.msg);
          }
        });
      } else {
        // 编辑
        roleedit(roleForm.value).then((res) => {
          if (res.code == 200) {
            // 成功 提示
            ElMessage.success(res.msg);
            // 成功-关闭弹窗
            cancel();
            store.dispatch("role/getRoleActions");
          } else {
            ElMessage.error(res.msg);
          }
        });
      }
    }
  });
};
// 可以通过defineExpose 编译器宏来显示指定在 <script setup> 组件中要暴露出去的属性
defineExpose({
  lookup,
});
</script>

<style lang="less" scoped>

</style>
